using UnityEngine;

[ExecuteInEditMode]
public class RollingBallSpawner : MonoBehaviour
{
	public GameObject rollingBall;

	public float delay;

	public float interval = 1f;

	public float intervalVariation;

	public float fallDistance = 100f;

	private bool isActive;

	private bool init = true;

	private float startTime;

	private bool running;

	private float lastIntervalTime;

	private float nextDuration;

	private void Awake()
	{
		LevelController.LevelReadyEvent += OnLevelReady;
		EventManager.WorldResetEvent += OnWorldReset;
	}

	private void OnDestroy()
	{
		LevelController.LevelReadyEvent -= OnLevelReady;
		EventManager.WorldResetEvent -= OnWorldReset;
	}

	private void OnLevelReady(Transform levelTransform)
	{
		if (base.transform.root == levelTransform)
		{
			Activate();
		}
	}

	private void OnWorldReset()
	{
		init = true;
		running = false;
	}

	public void Activate()
	{
		isActive = true;
	}

	private void FixedUpdate()
	{
		if (!isActive)
		{
			return;
		}
		if (init)
		{
			startTime = Time.time;
			init = false;
		}
		if (!init)
		{
			if (!running && Time.time - startTime - delay >= (0f - Time.fixedDeltaTime) / 2f)
			{
				running = true;
				lastIntervalTime = Time.time - interval;
				nextDuration = ((!(intervalVariation > 0f)) ? 0f : (Random.Range(0f, intervalVariation * 2f) - intervalVariation));
			}
			if (running && Time.time - lastIntervalTime - nextDuration >= (0f - Time.fixedDeltaTime) / 2f)
			{
				Shot();
				lastIntervalTime += interval;
				nextDuration = interval + ((!(intervalVariation > 0f)) ? 0f : (Random.Range(0f, intervalVariation * 2f) - intervalVariation));
			}
		}
	}

	private void Shot()
	{
		Vector3 position = base.transform.position;
		GameObject gameObject = Object.Instantiate(rollingBall) as GameObject;
		gameObject.transform.parent = base.transform;
		RollingBall component = gameObject.GetComponent<RollingBall>();
		component.destroyYLimit = 0f - fallDistance;
		gameObject.transform.rotation = base.transform.rotation * gameObject.transform.rotation;
		component.Shot(position);
	}
}
